local gamelib = require "club.threecard.gamelib"
local game = require "club.threecard.bjracing"

local phase_buttons = gamelib.ui.element()

local log = gamelib.logging.get("phase_buttons")

function phase_buttons:ctor(poker_container)
    self.res = "club.threecard.bjracing/ui/gamescene.b:phase_buttons";
    self.app = game;
    self.poker_container = poker_container;
end

phase_buttons.store_watchers = 
{
    ingame = 
    {
        ["on_ope_status"] = function(self, store, state, args)
            self:update_buttons(args);
        end,
        ["on_change_bet"] = function(self, store, state, args)
            self:update_bet();
         end
    }
}

function phase_buttons:on_injected(bind)
    bind("button.click", self.btn_bet, self.bet_ivk);
    bind("button.click", self.btn_see, self.see_ivk);
    bind("button.click", self.btn_exchange, self.exchange_ivk);

    bind("button.click", self.btn_bet_add, self.bet_add_ivk);
    bind("button.click", self.btn_bet_sub, self.bet_add_ivk);
end

function phase_buttons:update_bet()
    local index = game.store.ingame.state.selected_bet_index;
    local config = game.store.ingame.get_bet_config();
    local isMax = index >= #config;
    self.value_txt.text = config[index];
    self.max_tip:SetActive(isMax);
end

function phase_buttons:update_buttons(args)
    local can_see = args.can_see;
    local can_bet = args.can_bet;
    local can_exchange = args.can_exchange;

    self.btn_see.gameObject:SetActive(can_see);
    self.btn_bet.gameObject:SetActive(can_bet);
    self.btn_exchange.gameObject:SetActive(can_exchange);

    self.bet_value:SetActive(can_bet);
end

function phase_buttons:bet_ivk()
    local index = game.store.ingame.state.selected_bet_index;
    local config = game.store.ingame.get_bet_config();
    local value = config[index];

    game.kbe.player():bet(value);
end

function phase_buttons:see_ivk()
    local pokers = self.poker_container.hand;
    local flag = 0;
    for index, poker in ipairs(pokers) do
        if poker.selected then
            flag = flag | (1<<index-1)
        end
    end

    game.kbe.player():see(flag);
end

function phase_buttons:exchange_ivk()
    local pokers = self.poker_container:GetSelectedPoker();
    local t = {};
    for _, poker in ipairs(pokers) do
        table.insert(t, poker.data.server_value);
    end

    if #t == 0 then
        return;
    end

    game.kbe.player():exchange(t);
end

function phase_buttons:bet_add_ivk()
    game.store.ingame.on_change_bet({changed = 1});
end

function phase_buttons:bet_sub_ivk()
    game.store.ingame.on_change_bet({changed = -1});
end

return phase_buttons